<?php
if( !function_exists('tpl_parse_ext')) {
	function tpl_parse_ext($template){
		return template_ext($template);
	}
}
//模板扩展函数
function template_ext($template){
	//duxcms定义
	$duxcmsList=array(
		//普通转义
		'search' => array(
			//转义路径
			"/<(.*?)(src=|href=|value=|background=)[\"|\'](images\/|img\/|css\/|js\/|style\/)(.*?)[\"|\'](.*?)>/",
		),
		'replace' => array(
			"<$1$2\"".__ROOT__."/<?php echo \$config['TPL']['TPL_TEMPLATE_PATH'].\$siteInfo['tpl_dir']; ?>/"."$3$4\"$5>",
		),		
	);
	$template = preg_replace( $duxcmsList['search'], $duxcmsList['replace'], $template);
	//模板包含
	if(preg_match_all('/<!--#include\s*file=[\"|\'](.*)[\"|\']-->/', $template, $matches)){
		foreach ($matches[1] as $k => $v) {
			$ext=explode('.', $v);
			$ext=end($ext);
			$file=substr($v, 0, -(strlen($ext)+1));
			$phpText = '<?php echo $cpTemplate->display("'.$file.'"); ?>';
			$template = str_replace($matches[0][$k], $phpText, $template);
		}
	}
	//通用循环标签
	if(preg_match_all('/<!--([a-zA-z0-9_]+):{([^"].*)}-->/', $template, $matches)){
		//循环、赋值、输出
		foreach ($matches[2] as $k => $v) {
			$name=trim($matches[1][$k]);
			$v=trim($v);
			$v=$v.'#';
			$v=preg_replace('/\$(\w+)=/', '##$1#=', $v);
			if(preg_match_all('/\#(\w+)\#=(.*)#/U', $v, $mcs)){
				$phpText = '';
				$label = '';
				foreach ($mcs[1] as $key => $value) {
					$phpText .= '"'.$value.'"=>'.$mcs[2][$key].',';
					if($value=='label'){
						$label=$mcs[2][$key];
					}
					if($value=='empty'){
						$empty=$mcs[2][$key];
					}
				}					
			}
			if(!empty($label)&&strpos($label,'echo')){
				$phpText='<?php $'.$name.'=api(\'duxcms\',\'getTplLabel\',array('.$phpText.')); echo $'.$name.'[0]; ?>';
			}else if(!empty($label)&&strpos($label,'assign')){
				$phpText='<?php $'.$name.'=api(\'duxcms\',\'getTplLabel\',array('.$phpText.')); ?>';
			}else{
				$phpText='<?php $'.$name.'=api(\'duxcms\',\'getTplLabel\',array('.$phpText.')); if(empty($'.$name.')){ echo "'.$empty.'"; } if(isset($'.$name.') && is_array($'.$name.') && !empty($'.$name.')){ $'.$name.'_i=0; foreach($'.$name.' as $'.$name.'){ $'.$name.'_i++; $'.$name.'[i]=$'.$name.'_i; ?>';
			}
			$label='';
			$template = str_replace($matches[0][$k], $phpText, $template);
		}
	}
	//duxadmin定义
	$replaceList=array(
		//普通转义
		'search' => array(
			//常量括式
			'/\{\#(\w+)\#\}/',	
			//常量下划线
			'/__[A-Z]+__/',
			//去除注释标签
			'/<!--{(.+?)}-->/',
			//判断
			'/\{if="([^"]*)"\}/',
			'/\{elseif="([^"]*)"\}/',
			'/\{else\}/',
			'/\{\/if\}/',
			//循环
			'/\{\/([a-zA-z0-9_]+)\}/',
			//模板注释
			'/\{\*(.*?)\*\}/',
		),
		'replace' => array(
			"<?php echo $1; ?>",
			"<?php echo $0; ?>",
			'{$1}',
			"<?php if($1) { ?>",
			'<?php }elseif($1) { ?>',
			'<?php }else{ ?>',
			'<?php } ?>',
			'<?php }} ?>',
			'',
		)
	);
	$template = preg_replace( $replaceList['search'], $replaceList['replace'], $template);

	//解析循环标签
	if(preg_match_all('/{loop(?: name){0,1}="{0,1}([^"]*)"}/', $template, $matches)){
		foreach ($matches[1] as $k => $v) {
			$parameter=preg_replace("/\s+/"," ",$matches[1][$k]);
			$parameter=explode(' ',$parameter);
			$code='';
			if(count($parameter)<2){
				$parameter[1]='$key';
				$parameter[2]='$vo';
			}
			foreach ($parameter as $key => $value) {
				switch ($key) {
					case 0:
						$code.=$value;
						break;
					case 1:
						$code.=' as '.$value;
						$parameter2 = $value;
						break;
					case 2:
						$code.=' => '.$value;
						$parameter2 = $value;
						break;
				}			
			}

			$phpText = '<?php  if(isset('.$parameter[0].') && is_array('.$parameter[0].') && !empty('.$parameter[0].')){ '.$parameter2.'_i=0; foreach('.$code.'){ '.$parameter2.'_i++; '.$parameter2.'[i]='.$parameter2.'_i;  ?>';
			$template = str_replace($matches[0][$k], $phpText, $template);
		}
	}

	//转义变量 
	if (preg_match_all('/\{\$(\w+(?:\.\${0,1}[A-Za-z0-9_]+)*(?:(?:\[\${0,1}[A-Za-z0-9_]+\])|(?:\-\>\${0,1}[A-Za-z0-9_]+))*)(.*?)\}/',$template,$matches)){
	    for ($parsed = array(), $i = 0, $n = count($matches[0]); $i < $n; $i++)
            $parsed[$matches[0][$i]] = array('var' => $matches[1][$i], 'extraVar' => $matches[2][$i]); foreach ($parsed as $tag => $array) {
            $var = $array['var'];
            $extraVar = $array['extraVar'];
            //替换变量
            $newVar = '$'.preg_replace('/\.(\${0,1}\w+)/', '["\\1"]', $var);
            //是否为赋值
            $isVariable = preg_match("/^(\s*?)\=[^=](.*?)$/", $extraVar);
            //处理URL函数
            if($newVar=='$url'&&substr($extraVar,0,1) == '|'){
            	$url=substr($extraVar,1);
            	$newVar=$url;
            	$extraVar='|url';
            }
            //函数处理
            if(!empty($extraVar)&&substr($extraVar,0,1) == '|'){
            	$function = substr($extraVar,1);
            	$parameter = explode(':', $function,2);
            	$function = $parameter[0];
            	$parameter = $parameter[1];
            }else{
            	$function = null;
            }

            if($isVariable){
				$phpText = '<?php '.$newVar.$extraVar.'; ?>';
            }else if(!empty($function)){
            	if($parameter){
            		$phpText = '<?php echo '.$function.'('.$newVar.','.$parameter.'); ?>';
            	}else{
            		$phpText = '<?php echo '.$function.'('.$newVar.'); ?>';
            	}
            }else{
            	$phpText = '<?php echo '.$newVar.$extraVar.'; ?>';
            }
            $template = str_replace($tag, $phpText, $template);
        }

    }
	return $template;

}